package com.topcheer.common.auth.jwt;

import com.topcheer.common.auth.user.JwtUser;
import com.topcheer.common.base.CommonConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xutao
 * @Package com.topcheer.common.auth.jwt
 * @Description: ${todo}
 * @date 2020/4/8 10:38
 */
@Slf4j
public class JwtHelper {

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private static String generateToken(Map<String, Object> claims,byte[] primaryKeys,Long expiration) throws Exception{
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate).signWith(SignatureAlgorithm.RS256, RsaKeyHelper.getPrivateKey(primaryKeys))
                .compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private static Claims getClaimsFromToken(String token,byte[] pubKeys) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(RsaKeyHelper.getPublicKey(pubKeys)).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 生成令牌
     * @param userName 用户
     * @return 令牌
     */
    public static String generateToken(String userName,byte[] primaryKeys,Long expiration) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put(Claims.SUBJECT, userName);
        claims.put(Claims.ISSUED_AT, new Date());
        try{
            return generateToken(claims,primaryKeys,expiration);
        }catch (Exception e){
            log.error("generate token error |",e);
        }
        return null;
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public static String getUsernameFromToken(String token,byte[] pubKeys) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token,pubKeys);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public static Boolean isTokenExpired(String token,byte[] pubKey) {
        try {
            Claims claims = getClaimsFromToken(token,pubKey);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
   /* public String refreshToken(String token,byte[] primaryKeys,Long expiration) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT, new Date());
            refreshedToken = generateToken(claims,primaryKeys,expiration);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }*/

    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param jwtUser 用户
     * @return 是否有效
     */
    public static Boolean validateToken(String token, JwtUser jwtUser,byte[] pubKey) {
        String username = getUsernameFromToken(token,pubKey);
        return (username.equals(jwtUser.getUserName()) && !isTokenExpired(token,pubKey));
    }
}
